package com.itlong.cloud.controller.sdkV1.old.appClient;


import com.google.common.base.Joiner;
import com.itlong.cloud.POJO.DTO.app.old.AppOldUserInfoDto;
import com.itlong.cloud.POJO.DTO.sdk.old.SDKAppOldCallElevatorDTO;
import com.itlong.cloud.POJO.DTO.sdk.old.SDKAppOldOpenElevatorCmdDataDTO;
import com.itlong.cloud.POJO.DTO.sdk.old.SDKAppOldOpenElevatorInfoDTO;
import com.itlong.cloud.POJO.DTO.sdk.old.SDKAppOldOpenElevatorProtocolDTO;
import com.itlong.cloud.POJO.VO.property.AppUserGetDeviceAuthVO;
import com.itlong.cloud.POJO.VO.sdk.old.SDKAppOldElevatorInfoVO;
import com.itlong.cloud.POJO.VO.sdk.old.SDKAppOldOpenedElevatorVO;
import com.itlong.cloud.common.network.tcp.mina.IMinaServiceClient;
import com.itlong.cloud.enumerate.PropertyEquipTypeEnum;
import com.itlong.cloud.enumerate.oldapp.Code;
import com.itlong.cloud.enumerate.oldapp.Message;
import com.itlong.cloud.equip.app.IAppOldDeviceRecordServiceClient;
import com.itlong.cloud.equip.property.IPropertyDeviceAuthServiceClient;
import com.itlong.cloud.equip.sdk.ISDKAppOldEquipServiceClient;
import com.itlong.cloud.user.app.IAppOldRegisterServiceClient;
import com.itlong.cloud.user.sdk.ISDKAppOldUserServiceClient;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

;

/**
 * <desc>
 *    sdk-APP设备接口（如远程开门\上传通行记录\App自动呼梯）.
 * </desc>
 *
 * @createDate 2017-11-14
 */
@RestController
@RequestMapping("/jiabanjing/interface")
public class SDKAppOldEquipController {

    //日志记录对象
    private static final Logger LOG = LoggerFactory.getLogger(SDKAppOldEquipController.class);

    @Autowired
    IMinaServiceClient iMinaServiceClient;

    @Autowired
    IAppOldRegisterServiceClient iAppOldRegisterServiceClient;

    @Autowired
    IAppOldDeviceRecordServiceClient iAppOldDeviceRecordServiceClient;

    @Autowired
    ISDKAppOldUserServiceClient isdkAppOldUserServiceClient; //旧版APP_SDK用户服务暴露层接口

    @Autowired
    ISDKAppOldEquipServiceClient isdkAppOldEquipServiceClient; //旧版APP_SDK设备服务层暴露接口


    @Autowired
    IPropertyDeviceAuthServiceClient iPropertyDeviceAuthServiceClient; // 设备权限接口服务

    /**
     * <desc>
     *    APP SDK_远程开门
     * </desc>
     *
     * @param projectId 项目Id
     * @param auth 权限编码  开放2号电梯：{“auth”:”88888888,1,0002,F000000000000000000000000000, 2017-07-07 12:00:00,13756887635”}
                              开放1号门：{“auth”:”88888888,2,0001,8, 2017-07-07 12:00:00,13756887635”}
     * @return 标准格式化响应结果
     * @author LewisLouis
     * @createDate 2017-11-14
     */
//    @ResponseBody
//    @RequestMapping("/app/deviceAuth/authDevice")
//    public Message appAuthDevice(String projectId, String auth) {
//        JSONObject msg = new JSONObject();
//        msg.put("auth", auth);
//        Code c = iMinaServiceClient.oldSendMessage(projectId, msg.toJSONString());
//        return new Message(c);
//    }

    /**
     * <desc>
     *     上传通行记录
     * </desc>
     *
     * @param phoneNo 电话号码
     * @param recordJson 记录信息
     * @return 标准格式化响应结果
     * @author LewisLouis
     * @createDate 2017-11-14
     */
    @ResponseBody
    @RequestMapping("/app/deviceRecord/upload")
    public Message deviceRecordUpload(String phoneNo, String recordJson) throws Exception {
        if (StringUtils.isBlank(phoneNo) || (StringUtils.isEmpty(recordJson))){
            return new Message(Code.NOT_PARAM);
        }
        AppOldUserInfoDto appOldUserInfoDto = iAppOldRegisterServiceClient.selectDtoByPhone(phoneNo);
        if (appOldUserInfoDto == null){
            return new Message(Code.NOT_FOUNDUSER);
        }


        Message message = iAppOldDeviceRecordServiceClient.deviceRecordUpload(appOldUserInfoDto.getUserId(),recordJson);
        return  message;


    }

    /**
    * <desc>
    *      APP-SDK自动呼梯.
    * </desc>
    *
    * @param sdkAppOldCallElevatorDTO  APP-SDK远程自动呼梯数据传输对象.
    * @return 标准格式化响应结果
    * @author LewisLouis
    * @createDate 2017-11-15
    */
    @ResponseBody
    @RequestMapping("/app/deviceOperate/autoCallElevator")
    public Message autoCallElevator(SDKAppOldCallElevatorDTO sdkAppOldCallElevatorDTO) throws Exception{
        if ((null == sdkAppOldCallElevatorDTO)
                ||StringUtils.isEmpty(sdkAppOldCallElevatorDTO.getUserPhone())
                || StringUtils.isEmpty(sdkAppOldCallElevatorDTO.getProjectId())){
            return new Message(Code.NOT_PARAM);
        }
        AppOldUserInfoDto appOldUserInfoDto = iAppOldRegisterServiceClient.selectDtoByPhone(sdkAppOldCallElevatorDTO.getUserPhone());
        if (appOldUserInfoDto == null){
            return new Message(Code.NOT_FOUNDUSER);
        }

        //简化项目Id和用户Id调用
        String projectId = sdkAppOldCallElevatorDTO.getProjectId();
        String userId = appOldUserInfoDto.getUserId();


        //第一步获取软卡号
        String userCardNo = isdkAppOldUserServiceClient.getUserCardNo(userId,projectId);

        //第二步 获取服务与指定地址下（楼栋（1）、单元（n））的所有设备列表
        List<SDKAppOldElevatorInfoVO> elevatorUniques =  isdkAppOldEquipServiceClient.getDeviceUniquesByAddress(
                sdkAppOldCallElevatorDTO.getProjectId(),sdkAppOldCallElevatorDTO.getBuildNum(),sdkAppOldCallElevatorDTO.getUnitNum());

        //第三步 获取指定用户在该项目下的所有电梯设备权限
        List<AppUserGetDeviceAuthVO> appUserGetDeviceAuthVOS =
                iPropertyDeviceAuthServiceClient.getUserDeviceAuth(userId, projectId,
                        String.valueOf(PropertyEquipTypeEnum.ELEVATOR.getType()));

        //需要开放的设备信息（包括设备名称，楼层名称列表）列表,用于返回APP_SDK端
        List<SDKAppOldOpenedElevatorVO> sdkAppOldOpenedElevatorVOS =  new ArrayList<>();

        //需要发送给一卡通的开门协议内容
        SDKAppOldOpenElevatorProtocolDTO sdkAppOldOpenElevatorProtocolDTO = new SDKAppOldOpenElevatorProtocolDTO();
        sdkAppOldOpenElevatorProtocolDTO.setProjectId(projectId);
        sdkAppOldOpenElevatorProtocolDTO.setCmdType(1);
        SDKAppOldOpenElevatorCmdDataDTO sdkAppOldOpenElevatorCmdDataDTO = new SDKAppOldOpenElevatorCmdDataDTO();
        sdkAppOldOpenElevatorCmdDataDTO.setCardNo(userCardNo);

        //第四步 依次遍历地址下的设备，检查用户在该设备上是否具有liveFloor权限，若有则记录下来，组装发给一卡通的命令和返回给客户的数据
        for (SDKAppOldElevatorInfoVO sdkAppOldElevatorInfoVO:elevatorUniques){
            for (AppUserGetDeviceAuthVO appUserGetDeviceAuthVO:appUserGetDeviceAuthVOS){
                if (!StringHandlerUtil.compareStrWithOutEmpty(appUserGetDeviceAuthVO.getDeviceUnique(),
                        sdkAppOldElevatorInfoVO.getDeviceUnique())) {
                    //若没有当前设备权限，直接跳过
                    continue;
                }
                //若在当前电梯设备上拥有的楼层权限
                //创建单个设备信息对象，用于加入列表返回APP_SDK端
                SDKAppOldOpenedElevatorVO sdkAppOldOpenedElevatorVO = new SDKAppOldOpenedElevatorVO();
                sdkAppOldOpenedElevatorVO.setDeviceName(sdkAppOldElevatorInfoVO.getDeviceName());
                //创建单个设备对象，用于加入列表发送给一卡通
                SDKAppOldOpenElevatorInfoDTO sdkAppOldOpenElevatorInfoDTO = new SDKAppOldOpenElevatorInfoDTO();
                sdkAppOldOpenElevatorInfoDTO.setDeviceUnique(appUserGetDeviceAuthVO.getDeviceUnique());

                //****************开始处理当前设备的楼层********************
                //开放的楼层的逻辑名称列表，用于返回APP_SDK端
                List<String> openedlogicalfloorNameList = new ArrayList<>();
                //已授权的楼层逻辑名称列表
                List<String> authLogicalFloorList = Arrays.asList(appUserGetDeviceAuthVO.getLogicalFloor().split(","));
                if (StringUtils.isEmpty(sdkAppOldCallElevatorDTO.getLiveFloor())){
                    //指定开放的楼层列表为空时，直接取有权限的楼层列表开放
                    sdkAppOldOpenElevatorInfoDTO.setLiveChoiceFloor(appUserGetDeviceAuthVO.getNaturalFloor());
                    openedlogicalfloorNameList = authLogicalFloorList;

                } else {
                    //已授权的楼层权限标识列表
                    List<String> authfloorList = Arrays.asList(appUserGetDeviceAuthVO.getNaturalFloor().split(","));
                    //请求开放的楼层权限标识列表
                    List<String> livefloorList = Arrays.asList(sdkAppOldCallElevatorDTO.getLiveFloor().split(","));
                    //实际能够开放的楼层权限标识列表
                    List<String> canOpenfloorList = new ArrayList<>();

                    //遍历请求开放的楼层权限标识列表，判断是否在已授权的权限标识列表中，若已在，则记录下来
                    for (int livefloorIndex = 0;livefloorIndex < livefloorList.size();livefloorIndex++){
                        String livefloorNo = livefloorList.get(livefloorIndex);
                        int floorIndex = authfloorList.indexOf(livefloorNo);
                        if (floorIndex < 0)
                        {
                            //请求开放的楼层没有权限，则跳过
                            continue;
                        }
                        //取有权限的楼层开放，并记录逻辑名称
                        if (authLogicalFloorList.size() > floorIndex )
                        {
                            openedlogicalfloorNameList.add(authLogicalFloorList.get(floorIndex));
                        }
                        canOpenfloorList.add(livefloorNo);
                    }
                    if (!canOpenfloorList.isEmpty()){
                        sdkAppOldOpenElevatorInfoDTO.setLiveChoiceFloor(Joiner.on(",").join(canOpenfloorList));
                    }
                }

                //当前控制器，没有可开放的楼层，直接跳过
                if (StringUtils.isEmpty(sdkAppOldOpenElevatorInfoDTO.getLiveChoiceFloor())){
                   continue;
                }
                //将开放到设备信息加入列表，用于发送给一卡通
                sdkAppOldOpenElevatorCmdDataDTO.getDeviceList().add(sdkAppOldOpenElevatorInfoDTO);
                //给设备信息对象属性赋值，并加入列表，用于返回APP_SDK
                sdkAppOldOpenedElevatorVO.setFloorInfo(StringUtils.join(openedlogicalfloorNameList,','));
                sdkAppOldOpenedElevatorVOS.add(sdkAppOldOpenedElevatorVO);
            }
        }
        //完善发送给一卡通的数据
        sdkAppOldOpenElevatorCmdDataDTO.setTotalNumber(sdkAppOldOpenElevatorCmdDataDTO.getDeviceList().size());
        sdkAppOldOpenElevatorProtocolDTO.setCmdData(sdkAppOldOpenElevatorCmdDataDTO);


        //向一卡通发送数据
        Code sendMessage = iMinaServiceClient.oldSendMessage(projectId,JsonUtil.toJSON(sdkAppOldOpenElevatorProtocolDTO));
        //将发送结果和准备开放的设备信息返回给APP_SDK
        Map<String,Object> map=new HashMap<>();
        map.put("deviceInfo",sdkAppOldOpenedElevatorVOS);
        return new Message(sendMessage, map);
    }

}
